package com.qingguatang.java5minute.control;

import com.qingguatang.java5minute.model.Comment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

@Controller
public class CommentPostControl {
    private Map<String, List<Comment>> comments = new HashMap<>();

    @RequestMapping(value = "/comments/post")
    public String post(@RequestParam(value = "songId") String songId, Comment comment) {
        System.out.println("进入post");
        System.out.println(comment.getContent());
        System.out.println(songId);
        Date commentTime = new Date();
        comment.setCommentTime(commentTime);
        //xxx-xxx-xxx,36为可以全局唯一
        comment.setId(UUID.randomUUID().toString());
        // java8之后。上面的操作可以简化为一行，若key对应的value为空，会将第二个参数的返回值存入并返
        //完成数据的添加
        comments.computeIfAbsent(songId, k -> new ArrayList<>()).add(comment);
//        List<Comment> res;
//        if (comments.containsKey(songId)){
//            res=comments.get(songId);
//        }else {
//            res=new ArrayList<>();
//            comments.put(songId,res);
//        }
//        res.add(comment);
        List<Comment> commentList = comments.get(songId);
        Collections.sort(commentList, new Comparator<Comment>() {
            @Override
            public int compare(Comment o1, Comment o2) {
                if (o1.getCommentTime().after(o2.getCommentTime())) {
                    return 1;
                }
                return -1;
            }
        });
        return "redirect:/comments";
    }

    public List<Comment> getComments(String songId) {
        return comments.get(songId);
    }
}
